package com.elong.android.specialhouse.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.LogWriter;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.ApartmentListAdapter;
import com.elong.android.specialhouse.adapter.ApartmentListAdapter.OnCollectionListener;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.ApartmentDatepickerParam;
import com.elong.android.specialhouse.entity.ApartmentKeyword;
import com.elong.android.specialhouse.entity.ApartmentListResponse;
import com.elong.android.specialhouse.entity.ApartmentSearchChildDataInfo;
import com.elong.android.specialhouse.entity.ApartmentSearchParam;
import com.elong.android.specialhouse.entity.ApartmentSelectSerchChildInfo;
import com.elong.android.specialhouse.entity.FilterCondition;
import com.elong.android.specialhouse.entity.HouseInfoRequestParam;
import com.elong.android.specialhouse.entity.HouseItemList;
import com.elong.android.specialhouse.request.CollectionReq;
import com.elong.android.specialhouse.utils.ApartmentAreaUtils;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.EventReportTools;
import com.elong.framework.net.error.NetFrameworkError;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.request.RequestOption;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.infrastructure.entity.Group;
import com.nineoldandroids.view.ViewPropertyAnimator;

import java.util.ArrayList;
import java.util.List;

public class ApartmentListActivity extends BaseVolleyActivity<IResponse<?>>
        implements OnClickListener, OnItemClickListener,View.OnTouchListener{
    private static final String PAGE_NAME = "youfangListPage";
    // StartActivityForResult标志
    public final static int ACTIVITY_LOGIN = 0;
    public final static int ACTIVITY_SEARCH = 1;
    public final static int ACTIVITY_DATE = 2;
    public final static int ACTIVITY_FILTER = 3;
    public final static int ACTIVITY_DETAILS = 4;
    private static final int JSONTASK_SEARCHLIST = 1;
    private static final int JSONTASK_ADD_COLLECTION = 2;
    private static final int JSONTASK_DEL_COLLECTION = 3;

    private int m_old_houseListTop = 0;
    private int m_old_houseListSelection = 0;
    public int m_itemsDisplayedLimit = 15;
    // 列表滑动到倒数第几项开始预加载下一页数据
    private int m_refreshStartPosition = -5;

    private int oldFirstPos = -1, oldLastPost = -1;
    // 是否滑到倒数第5条数据(从列表页倒数第五条数据开始预加载)
    boolean isLastRow = false;
    boolean isRefresing = false;
    // 记录是否显示过没有结果的tips提示
    boolean isAlreadyShowNoResultTips = false;
    private LinearLayout llListHeader;
    private RelativeLayout rlListFilter;
    private ImageView ivFilterRedDot;
    private LinearLayout llCheckDate;
    private ListView lvApartmentList;
    private ImageView commonSearch;
    private ImageView ivSearchRedDot;
    private TextView tvCheckInDate, tvCheckOutDate;
    private View m_footerView;

    private ApartmentListAdapter m_baseAdapter;
    private List<HouseItemList> mHouseItem;
    private ApartmentSearchParam mSearchParam = null;
    private ApartmentListResponse mSearchResponse;
    private FilterCondition mFilterCondition = null;

    /**
     * **************************************************************
     * 以下是屏幕浏览过的View打点 逻辑：调用onscroll的方法，记录所有的可见Item，去重相邻记录，之后，统计相邻记录新出现的酒店
     * **************************************************************
     */
    private ArrayList<Integer> pos = new ArrayList<Integer>();

    // 搜索关键词信息
    private ApartmentKeyword mKeyWordInfo = null;

    private ApartmentSelectSerchChildInfo mSSInfo;

    private int lastClickedItemPos = -1;
    private ImageView ivMessage;
    private boolean isToolsHide = false;
    private GestureDetector mGestureDetector ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventReportTools.sendPageOpenEvent(PAGE_NAME);
        mGestureDetector = new GestureDetector(this, new MyGestureListener());
        mSearchParam = (ApartmentSearchParam) getIntent().getSerializableExtra(
                "ApartmentSearchParam");
        if (mSearchParam == null) {
            mSearchParam = new ApartmentSearchParam();
        } else {
            setHeader(mSearchParam.getCityName());
        }
        setHeader(TextUtils.isEmpty(mSearchParam.CityName)? "" :mSearchParam.CityName);
        mSearchParam.PageSize = m_itemsDisplayedLimit;
        setCheckInOutData(mSearchParam);

        if (getIntent().hasExtra("SelectSerchChildInfo")) {
            mSSInfo = (ApartmentSelectSerchChildInfo) getIntent()
                    .getSerializableExtra("SelectSerchChildInfo");
        } else {
            Group<ApartmentSearchChildDataInfo> childDataInfos = new Group<ApartmentSearchChildDataInfo>();
            mSSInfo = new ApartmentSelectSerchChildInfo(childDataInfos);
        }
        productRequest();
    }

    private void productRequest() {
        mSearchParam.PageIndex = ((mSearchResponse == null || mSearchResponse
                .getHouseItemList() == null) ? 0 : (mSearchResponse
                .getHouseItemList().size() == 0) ? 0 : (((mSearchResponse
                .getHouseItemList().size() - 1) / m_itemsDisplayedLimit) + 1));
        if (Account.getInstance().isLogin()) {
            mSearchParam.UserId = Account.getInstance().getUserId();
        }
        RequestOption requestOption = new RequestOption();
        JSONObject params = (JSONObject) JSON.toJSON(mSearchParam);
        requestOption.setJsonParam(params);
        requestOption.setTag(JSONTASK_SEARCHLIST);
        requestHttp(requestOption, ApartmentAPI.searchList,
                StringResponse.class, true);
    }

    private void setCheckInOutData(ApartmentSearchParam param) {
        tvCheckInDate.setText(DateTimeUtils.getMonthAndDay(param.CheckInDate));
        tvCheckOutDate
                .setText(DateTimeUtils.getMonthAndDay(param.CheckOutDate));
    }

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_apartment_list);
        rlListFilter = (RelativeLayout) findViewById(R.id.rl_list_filter);
        ivFilterRedDot = (ImageView) findViewById(R.id.iv_filter_red_dot);
        commonSearch = (ImageView) findViewById(R.id.common_search);
        ivSearchRedDot = (ImageView) findViewById(R.id.iv_search_red_dot);
        llListHeader = (LinearLayout) findViewById(R.id.ll_list_header);
        tvCheckInDate = (TextView) findViewById(R.id.tv_check_in_date);
        tvCheckOutDate = (TextView) findViewById(R.id.tv_check_out_date);
        llCheckDate = (LinearLayout) findViewById(R.id.ll_check_date);
        commonSearch.setVisibility(View.VISIBLE);
        rlListFilter.setOnClickListener(this);
        commonSearch.setOnClickListener(this);
        llCheckDate.setOnClickListener(this);
        ivMessage = (ImageView) findViewById(R.id.common_message);
        ivMessage.setVisibility(View.VISIBLE);
        initListView();
    }

    private void initListView() {
        lvApartmentList = (ListView) getListView();
        lvApartmentList.setOnItemClickListener(this);
        lvApartmentList.setOnTouchListener(this);
        lvApartmentList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    // 列表下拉出现headerview时，显示工具栏
                    showTools();
                }
                if (hasMoreItems()
                        && totalItemCount > 0
                        && firstVisibleItem > 0
                        && (firstVisibleItem + visibleItemCount >= totalItemCount
                        + m_refreshStartPosition) && !isRefresing) {
                    isLastRow = true;
                }

                if (totalItemCount > 0
                        && firstVisibleItem > 0
                        && (firstVisibleItem + visibleItemCount >= totalItemCount)
                        && !isRefresing && !isAlreadyShowNoResultTips
                        && !hasMoreItems()) {
                    Toast.makeText(ApartmentListActivity.this,
                            R.string.no_more_houses, Toast.LENGTH_LONG).show();
                    isAlreadyShowNoResultTips = true;
                }
                recordCountlyPoints(firstVisibleItem, firstVisibleItem
                        + visibleItemCount);
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isLastRow) {
                    m_old_houseListSelection = view.getFirstVisiblePosition();
                    View firstItem = view.getChildAt(0);
                    m_old_houseListTop = (firstItem == null ? 0 : firstItem
                            .getTop());
                    productRequest();
                    isLastRow = false;
                    isRefresing = true;
                }
            }
        });

        //为ListView添加一个透明的Header，与llListHeader一样高。这样列表中的第一个元素不被遮住
        View header = new View(this);
        header.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, px(48)));
        header.setBackgroundColor(Color.parseColor("#00000000"));
        lvApartmentList.addHeaderView(header);
        m_footerView = this.getListFooter();
        setFooterViewText(R.string.more_house);
    }
    private int px(float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }
    /**
     * 记录索引
     */
    protected void recordCountlyPoints(int firstVisibleItemPos,
                                       int lastVisibleItemPos) {
        // 没滑动
        if (oldFirstPos == firstVisibleItemPos) {
            return;
        } else if (firstVisibleItemPos > oldFirstPos) {// 下滑
            while (lastVisibleItemPos - oldLastPost > 0) {
                pos.add(++oldLastPost);
            }
        } else {// 上滑
            while (oldFirstPos - firstVisibleItemPos > 0) {
                pos.add(--oldFirstPos);
            }
        }
        oldFirstPos = firstVisibleItemPos;
        oldLastPost = lastVisibleItemPos;
    }

    protected View getListFooter() {
        return LayoutInflater.from(this).inflate(R.layout.list_footer, null);
    }

    protected void setFooterViewText(int resId) {
        ((TextView) m_footerView.findViewById(R.id.list_footer)).setText(resId);
    }

    protected AdapterView getListView() {
        return (ListView) findViewById(R.id.lv_apartment_list);
    }

    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_list_filter:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "filter");//筛选filter
                if (mFilterCondition == null) {
                    mFilterCondition = new FilterCondition();
                }
                Intent filterIntent = new Intent(this,
                        ApartmentFilterActivity.class);
                filterIntent.putExtra("FilterCondition", mFilterCondition);
                startActivityForResult(filterIntent, ACTIVITY_FILTER);
                break;
            case R.id.common_search:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "search");//搜索search
                Intent searchIntent = new Intent(this,
                        ApartmentAreaSelectActivity.class);
                searchIntent.putExtra(AppConstants.BUNDLEKEY_CITYNAME,
                        mSearchParam.getCityName());
                searchIntent.putExtra(AppConstants.BUNDLEKEY_CITYID,
                        mSearchParam.getCityID());
                if (mSSInfo != null) {
                    // 这个Extra只做显示用,所以清楚里面除"区域位置"以外的数据
                    searchIntent.putExtra("selectedNode", mSSInfo);
                }
                startActivityForResult(searchIntent, ACTIVITY_SEARCH);
                break;
            case R.id.ll_check_date:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "arriveLeaveTime");//入离时间arriveLeaveTime
//                Calendar calendar = Calendar.getInstance();
//                long startDay = calendar.getTimeInMillis();
//                calendar.add(Calendar.MONTH, 3);
//                calendar.add(Calendar.DAY_OF_YEAR, -2);
//                long endDay = calendar.getTimeInMillis();
//                int dayPast = (int) ((endDay - startDay) / (24 * 60 * 60 * 1000));
                Bundle bundle = new Bundle();
                ApartmentDatepickerParam value = new ApartmentDatepickerParam();
                value.checkInDate = mSearchParam.CheckInDate;
                value.checkOutDate = mSearchParam.CheckOutDate;
                value.startDate = DateTimeUtils.getCurrentDateTime();
//                value.dateRange = 90 + dayPast;
                value.dateRange = 180;
                value.currentCityType = AppConstants.CITYTYPE_APARTMENT;
                bundle.putSerializable(ApartmentDatepickerParam.TAG, value);
                bundle.putBoolean(AppConstants.ACTIVITY_KEY_IS_SHOW_PRICE, false);
                myStartActivityForResult(DatePickerActivity.class, bundle,
                        ACTIVITY_DATE);
                break;
            case R.id.common_message:
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "message");//消息message
                break;
        }
    }
    @Override
    public void back(){
        EventReportTools.sendPageSpotEvent(PAGE_NAME, "back");//返回back
        super.back();
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if(position > 0) {
            goTODetails(position - 1);
            lastClickedItemPos = position - 1;
        }
    }

    private void goTODetails(int position) {
        Intent intent = new Intent(this, ApartmentDetailsActivity.class);
        HouseInfoRequestParam param = new HouseInfoRequestParam();
        param.HouseItemList = mSearchResponse.HouseItemList.get(position);
        param.CheckInDate = mSearchParam.CheckInDate;
        param.CheckOutDate = mSearchParam.CheckOutDate;
        intent.putExtra("ApartmentInfoRequestParam", param);
        startActivityForResult(intent, ACTIVITY_DETAILS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ACTIVITY_SEARCH:
                    clearLocalApartmentData();

                    if (data.hasExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT)) {
                        mKeyWordInfo = (ApartmentKeyword) data
                                .getSerializableExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT);
                        mSearchParam.setKeywordPara(mKeyWordInfo);
                        mSSInfo = ApartmentAreaUtils
                                .changeToSelectSerchChildInfo(mKeyWordInfo);
                        productRequest();
                    }
                    if(mKeyWordInfo.isEmptyKeyWord()){
                        ivSearchRedDot.setVisibility(View.GONE);
                    }else{
                        ivSearchRedDot.setVisibility(View.VISIBLE);
                    }
                    break;
                case ACTIVITY_DATE:
                    if (data != null) {
                        clearLocalApartmentData();
                        Bundle bdDate = data.getExtras();
                        ApartmentDatepickerParam param = (ApartmentDatepickerParam) bdDate
                                .get(ApartmentDatepickerParam.TAG);
                        mSearchParam.setCheckInDate(param.checkInDate);
                        mSearchParam.setCheckOutDate(param.checkOutDate);
                        setCheckInOutData(mSearchParam);
                        m_old_houseListTop = 0;
                        m_old_houseListSelection = 0;
                        productRequest();
                    }
                    break;
                case ACTIVITY_FILTER:
                    if (data == null) {
                        return;
                    }
                    clearLocalApartmentData();
                    Bundle bdFilter = data.getExtras();
                    mFilterCondition = (FilterCondition) bdFilter
                            .get("FilterCondition");
                    if (mFilterCondition.isClear()) {
                        //取消红点
                        ivFilterRedDot.setVisibility(View.GONE);
                    } else {
                        //显示红点
                        ivFilterRedDot.setVisibility(View.VISIBLE);
                    }
                    mSearchParam.setFilterCondition(mFilterCondition);
                    m_old_houseListTop = 0;
                    m_old_houseListSelection = 0;
                    productRequest();
                    break;
                case ACTIVITY_DETAILS:
                    if (data != null) {
                        boolean isCollection = data.getBooleanExtra(
                                ApartmentDetailsActivity.KEY_IS_MODIFY_COLLECTION,
                                false);
                        if (lastClickedItemPos != -1) {
                            m_baseAdapter.getItem(lastClickedItemPos).IsCollected = isCollection;
                            m_baseAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void clearLocalApartmentData() {
        // -------开始记录view记录打点数据
        oldFirstPos = -1;
        oldLastPost = -1;
        // -------结束记录view记录打点数据

        if (mSearchResponse != null) {
            mSearchResponse.clearHouseData();
        }

        if (m_baseAdapter != null) {
            m_baseAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        if (lvApartmentList != null && m_footerView != null) {
            lvApartmentList.removeFooterView(m_footerView);
        }
        if (t == null) {
            return;
        }
        JSONObject result = null;
        try {
            result = (JSONObject) JSONObject.parse(((StringResponse) t)
                    .getContent());
        } catch (JSONException e) {
            LogWriter.logException(TAG, "", e);
            return;
        }
        Object tag = request.getRequestOption().getTag();
        if (checkJSONResponse(result) && tag instanceof Integer) {
            switch ((Integer) tag) {
                case JSONTASK_SEARCHLIST:
                    onRefresh(result);
                    break;
                case JSONTASK_ADD_COLLECTION:
                    if (result != null
                            && !result.getBoolean(JSONConstants.ATTR_ISERROR)) {
                        if (result.containsKey(JSONConstants.ATTR_INDEX)) {
                            int index = result
                                    .getIntValue(JSONConstants.ATTR_INDEX);
                            ((HouseItemList) m_baseAdapter.getItem(index)).IsCollected = true;
                            m_baseAdapter.notifyDataSetChanged();
                        }
                        Toast.makeText(this, R.string.add_collection_success,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, R.string.add_collection_success,
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
                case JSONTASK_DEL_COLLECTION:
                    if (result != null
                            && !result.getBoolean(JSONConstants.ATTR_ISERROR)) {
                        if (result.containsKey(JSONConstants.ATTR_INDEX)) {
                            int index = result
                                    .getIntValue(JSONConstants.ATTR_INDEX);
                            ((HouseItemList) m_baseAdapter.getItem(index)).IsCollected = false;
                            m_baseAdapter.notifyDataSetChanged();
                        }
                        Toast.makeText(this, R.string.cancel_collection_success,
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, R.string.cancel_collection_failed,
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    }

    @Override
    public void onTaskError(ElongRequest request, NetFrameworkError ex) {
        super.onTaskError(request, ex);
        Log.i(TAG, "onTaskError");
        if (request.getRequestOption().getHusky() == ApartmentAPI.searchList) {
            if (lvApartmentList != null && m_footerView != null) {
                lvApartmentList.removeFooterView(m_footerView);
            }
        }
    }

    private void onRefresh(Object response) {
        if (response != null) {
            JSONObject obj = (JSONObject) response;
            ApartmentListResponse newResult = JSON.toJavaObject(obj,
                    ApartmentListResponse.class);
            if (newResult == null) {
                newResult = new ApartmentListResponse();
            }
            if (newResult.HouseItemList == null) {
                newResult.HouseItemList = new ArrayList<HouseItemList>();
            }
            if (mSearchResponse != null) {
                if (mSearchResponse.HouseItemList == null) {
                    mSearchResponse.HouseItemList = new ArrayList<HouseItemList>();
                }
                mSearchResponse.HouseCount = newResult.HouseCount;
                mSearchResponse.HouseItemList.addAll(newResult.HouseItemList);
            } else {
                mSearchResponse = newResult;
            }
            this.refreshListView();
        }
        isRefresing = false;
        isAlreadyShowNoResultTips = false;
    }

    /**
     * @return void
     * @throws
     * @Title: refreshListView
     * @Description: TODO
     */
    private void refreshListView() {
        ViewSwitcher switcher = (ViewSwitcher) this
                .findViewById(R.id.house_list_listswitcher);
        if (this.hasNoLocalHouse()) {
            switcher.setDisplayedChild(1);
            return;
        } else {
            switcher.setDisplayedChild(0);
        }
        if (this.m_baseAdapter == null) {
            m_baseAdapter = createMyAdapter();
        }
        lvApartmentList.removeFooterView(m_footerView);
        // 加载更多...
        if (this.hasMoreItems()) {
            lvApartmentList.addFooterView(m_footerView);
        } else {
            lvApartmentList.removeFooterView(m_footerView);
        }

        m_baseAdapter.setOnCollectionClickListener(new OnCollectionListener() {
            @Override
            public void onCollectinClicked(HouseItemList item, int position) {
                CollectionReq req = new CollectionReq();
                EventReportTools.sendPageSpotEvent(PAGE_NAME, "collection");//收藏collection
                if (!Account.getInstance().isLogin()) { // 未登录，跳转到登录页面
                    Intent intent = new Intent(ApartmentListActivity.this,
                            LoginActivity.class);
                    intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, TAG);
                    startActivity(intent);
                    return;
                }
                req.UserId = Account.getInstance().getUserId();
                req.HouseId = item.HouseId;
                req.Index = position;
                if (item.IsCollected) {
                    req.setTag(JSONTASK_DEL_COLLECTION);
                    requestHttp(req, ApartmentAPI.deleteCollectionInfo,
                            StringResponse.class);
                } else {
                    req.setTag(JSONTASK_ADD_COLLECTION);
                    requestHttp(req, ApartmentAPI.addCollectionInfo,
                            StringResponse.class);
                }
            }
        });
        lvApartmentList.setAdapter(m_baseAdapter);
        m_baseAdapter.notifyDataSetChanged();
        lvApartmentList.setSelectionFromTop(m_old_houseListSelection,
                m_old_houseListTop);
    }

    protected boolean hasMoreItems() {
        if (this.mSearchResponse != null
                && this.mSearchResponse.HouseItemList != null) {
            return mSearchResponse.HouseCount > 0
                    && (mSearchResponse.HouseCount
                    - mSearchResponse.HouseItemList.size() > 0);
        } else {
            return false;
        }

    }

    /**
     * @param @return
     * @return ApartmentListAdapter
     * @throws
     * @Title: createMyAdapter
     * @Description: 创建adapter
     */
    private ApartmentListAdapter createMyAdapter() {
        return new ApartmentListAdapter(this, mSearchResponse);
    }

    private boolean hasNoLocalHouse() {
        return (mSearchResponse == null
                || mSearchResponse.getHouseItemList() == null || mSearchResponse
                .getHouseItemList().size() == 0);
    }

    @Override
    protected int getReceiverPriority() {
        return AppConstants.RECEIVER_PRIORITY_HOME;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (mGestureDetector != null) {
            return mGestureDetector.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            // 列表上滑没有headerview时，才判断工具栏显示或隐藏
            if (lvApartmentList.getFirstVisiblePosition() > 0) {
                if (e1 != null && e2 != null && llListHeader != null) {
                    if (e1.getY() - e2.getY() > 10 && Math.abs(velocityY) > 10) {//上滑
                        hideTools();
                    } else if (e2.getY() - e1.getY() > 10 && Math.abs(velocityY) > 10) {//下滑
                        showTools();
                    }
                }
            }
            return false;
        }
    }
    /**
     * 显示工具栏
     */
    private void showTools() {
        if(isToolsHide){
            ViewPropertyAnimator.animate(llListHeader).setDuration(200).translationY(0).start();
        }
        isToolsHide = false;
    }

    /**
     * 隐藏工具栏
     */
    private void hideTools() {
        if(!isToolsHide){
            ViewPropertyAnimator.animate(llListHeader).setDuration(500).translationY(-llListHeader.getHeight()).start();
        }
        isToolsHide = true;
    }
}
